package cn.ii8080.i8.oauth2.server.vo;

import com.alibaba.fastjson.JSON;
import org.springframework.util.ObjectUtils;

import java.io.Serializable;

/**
 * @param <T>
 */
public class ResponseVo<T> implements Serializable {
    //成功返回码
    public static int SUCCESS = 0;
    //成功文本描述
    public static String SUCCESS_MSG = "SUCCESS";
    //失败返回码
    public static int FAIL = -1;
    //失败返回描述
    public static String FAIL_MSG = "FAIL";
    //返回码
    private int code;
    //文本描述
    private String msg;
    //数据
    private T data;
    //时间
    private long time;

    /**
     * 默认是成功状态
     */
    public ResponseVo() {
        rest(null, SUCCESS, SUCCESS_MSG);
    }

    /**
     * @param bool true:成功 false:失败
     */
    public ResponseVo(boolean bool) {
        if (bool) {
            rest(null, SUCCESS, SUCCESS_MSG);
        } else {
            rest(null, FAIL, FAIL_MSG);
        }
    }

    /**
     * 默认是成功状态
     *
     * @param data 返回的数据
     */
    public ResponseVo(T data) {
        if (ObjectUtils.isEmpty(data)) {
            rest(null, FAIL, FAIL_MSG);
        } else {
            rest(data, SUCCESS, SUCCESS_MSG);
        }
    }

    /**
     * @param data
     * @return 返回成功后的数据
     */
    public ResponseVo<T> success(T data) {
        return rest(data, SUCCESS, SUCCESS_MSG);
    }

    /**
     * @param data
     * @return 返回失败后的数据
     */
    public ResponseVo<T> fail(T data) {
        return rest(data, FAIL, FAIL_MSG);
    }

    private ResponseVo<T> rest(T data, int code) {
        return rest(data, code, null);
    }

    private ResponseVo<T> rest(T data, int code, String msg) {
        this.data = data;
        this.code = code;
        this.msg = msg;
        this.time = System.currentTimeMillis();
        return this;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public long getTime() {
        return time;
    }

    public void setTime(long time) {
        this.time = time;
    }

    public String toJSONString() {
        return JSON.toJSONString(this);
    }

    public Object toJSON() {
        return JSON.toJSON(this);
    }
}
